package com.moyun.zbmy.zizhou.ui.activities;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Cache;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.base.BaseActivity;
import com.moyun.zbmy.zizhou.beans.FRebellion;
import com.moyun.zbmy.zizhou.beans.FUsers;
import com.moyun.zbmy.zizhou.beans.SingleResult;
import com.moyun.zbmy.zizhou.beans.TopicContent;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.http.ParamsEditor;
import com.moyun.zbmy.zizhou.ui.adapter.ShareAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.holder.ShareHolder;
import com.moyun.zbmy.zizhou.ui.adapter.holder.TopicHolder;
import com.moyun.zbmy.zizhou.ui.dialog.ConfirmFragment;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.ui.utils.SkipUtil;
import com.moyun.zbmy.zizhou.utils.UserManager;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 爆料搜索
 */

public class SearchTipOffActivity extends BaseActivity implements  CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, TopicHolder.OnTopicSelectListener , CanRefreshLayout.IScrollView{

    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    @BindView(R.id.input_key)
    EditText searchKeyCt;
    @BindView(R.id.search_cancel)
    CustomFontTextView searchCancel;
    @BindView(R.id.rebllion_list)
    RecyclerView rebllionList;
    @BindView(R.id.rebllion_refresh)
    CanRefreshLayout rebllionRefresh;
    private ShareAdapter mAdapter;
    private boolean mIsLoading = false;
    private int mPageNo = 0;
    private int mPageAll = 0;
    private int count = 10;
    private final static int pageSize = 10;
    private List<IListShowData> dataList = new ArrayList<>();
    private ConfirmFragment confirmFragment;
    public static final String REPORT_TAG = "report_fragment";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tip_off);
        ButterKnife.bind(this);
        rebllionRefresh.setOnRefreshListener(this);
        rebllionRefresh.setOnLoadMoreListener(this);
        rebllionRefresh.setLoadMoreEnabled(false);
        detail.setiScrollView(this);
        rebllionList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rebllionList.setItemAnimator(new DefaultItemAnimator());
    }

    @OnClick(R.id.search_cancel)
    public void onViewClicked(View view) {
       if(view==searchCancel){
           finish();
       }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            String key = searchKeyCt.getText().toString().trim();
            if (TextUtils.isEmpty(key)) {
                toast("搜索关键词不能为空");
                return false;
            }
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("行为类型", "主动搜索"));
            GridsumWebDissector.getInstance().trackEvent(SearchTipOffActivity.this, "", "搜索", "", 200, pairs);
            rebllionRefresh.autoRefresh();
//            addHistory(key)
        }
        return super.dispatchKeyEvent(event);
    }
    private void getData(String keyword) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("size", count);
        param.put("page", mPageNo);
        param.put("siteNumber", Constances.SITE_ID);
        param.put("keyword", keyword);
        NetUtils.getNetAdapter().searchTopiciscloseList(getOwnerName(), param, new AbsListNetCallback<FRebellion>(FRebellion.class) {
            @Override
            public void onSuc(List<FRebellion> fRebellions) {
                if (fRebellions == null || fRebellions.size() == 0) {
                    initData(null);
                    return;
                }
                if (mPageAll == 0) {
                    mPageAll = getPageResponse().getData().getPageAll();
                }
                initData(fRebellions);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(R.string.loading_no_data);
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });

    }
    private synchronized void onNetFinish() {
        mIsLoading = false;
        rebllionRefresh.refreshComplete();
        rebllionRefresh.loadMoreComplete();
        rebllionRefresh.setLoadMoreEnabled(mPageNo < mPageAll);
    }
    private void initData(List<FRebellion> fRebellions) {
        if (fRebellions == null || fRebellions.size() == 0) {
            fRebellions = new ArrayList<>();
            toast("未搜索到包含搜索词的信息");
        }

        dataList.addAll(fRebellions);
        if (0 < dataList.size()) {
            rebllionRefresh.setVisibility(View.VISIBLE);
//            contentnoLayout.setVisibility(View.GONE);
        } else {
            rebllionRefresh.setVisibility(View.GONE);
//            contentnoLayout.setVisibility(View.VISIBLE);
        }

        if (mAdapter == null) {
            mAdapter = new ShareAdapter(SearchTipOffActivity.this, dataList, this).setItemInternalClick(itemClick);
            rebllionList.setAdapter(mAdapter);
        }
        if (mPageNo == 0) {
            mAdapter.setData(dataList);
        } else if (ListUtils.isListValued(fRebellions)) {
            List<IListShowData> list = new ArrayList<>();
            list.addAll(fRebellions);
            mAdapter.addDatas(list);
        }
        mAdapter.notifyDataSetChanged();
        mPageNo++;
    }

    OnItemInternalClick itemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            switch (view.getId()) {
                case R.id.item_rebllion_video_play:
                    itemPlayClick(itemView, view, position);
                    break;
                case R.id.li_doup:
                    if (!UserManager.isLoginS()) {
                        toLogin();
                        return;
                    }
                    if (mAdapter.getItem(position) instanceof FRebellion) {
                        FRebellion fr = (FRebellion) mAdapter.getItem(position);
                        doUp(fr, position);
                    }
//                    doUp(mAdapter.getItem(position), position);
                    break;
                case R.id.tv_anchor_comment:
                    if (!UserManager.isLoginS()) {
                        toLogin();
                        return;
                    }
                    if (mAdapter.getItem(position) instanceof FRebellion) {
                        FRebellion fr = (FRebellion) mAdapter.getItem(position);
                        Intent intent = new Intent(SearchTipOffActivity.this, ShareDetailActivity.class);
                        intent.putExtra(EX_DATA, fr);
                        intent.putExtra(EX_COMMENT_TYPE, 4);
                        intent.putExtra(DO_UP_POS, position);
                        startActivity(intent);
                    }
                    break;
                case R.id.tv_report:
                    if (!UserManager.isLoginS()) {
                        toLogin();
                        return;
                    }
                    showConfirm(position);
                    break;

            }
        }
    };
    private void showConfirm(int position) {
        if (confirmFragment == null) {
            confirmFragment = new ConfirmFragment();
        }
        confirmFragment.setCallBack(callBack);
        confirmFragment.setPosition(position);
        confirmFragment.show(this.getSupportFragmentManager(), REPORT_TAG);
    }
    //Dialog点击回调
    public BaseDialogFragment.ICallBack callBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            doReport(msg.what);
        }
    };

    private void doReport(int position) {
        if (mAdapter.getItem(position) instanceof FRebellion) {
            FRebellion fRebellion = (FRebellion) mAdapter.getItem(position);
            if (fRebellion != null) {
                SkipUtil.skipToAddUserOperate(this, getOwnerName(), 17, 3, "举报", ((FRebellion) mAdapter.getItem(position)).getInfoId(), Cache.getInstance().getCurrentChannelId());

            }
        }

    }
    private void itemPlayClick(View itemView, View view, int position) {
        if (mAdapter.getItem(position) instanceof FRebellion) {
            FRebellion fRebellion = (FRebellion) mAdapter.getItem(position);
            if (fRebellion != null) {
                SkipUtil.skipToVideoPlayWithCover(this, UrlUtils.linkUrls(Constances.ST_BASE_URL, fRebellion.getDiscloseVideo())
                        , fRebellion.getPlayedPos(), position, fRebellion.getCoverImage());
            }
        }
    }

    private ShareHolder lastHolder = null;
    Drawable showIcon = null;
    private void doUp(final FRebellion aDynamicsItem, final int position) {
        ParamsEditor pe = new ParamsEditor();
        pe.put("dynamicId", aDynamicsItem.getInfoId());
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        pe.put("fType", 2);

        RecyclerView.LayoutManager manager = rebllionList.getLayoutManager();
        View lastView = manager.findViewByPosition(position);

        if (null != lastView) {
            lastHolder = (ShareHolder) rebllionList.getChildViewHolder(lastView);
            if (null != lastHolder) {
                lastHolder.tv_anchor_up.setDrawableEnlarge();
            }
        }


        NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult singleResult) {
                if (singleResult.isSuccess()) {

                    RecyclerView.LayoutManager manager = rebllionList.getLayoutManager();
                    View lastView = manager.findViewByPosition(position);

                    ShareHolder lastHolder = null;
                    if (mAdapter.getItem(position) instanceof FRebellion) {
                        FRebellion fr = (FRebellion) mAdapter.getItem(position);

                        if (null != lastView) {
                            lastHolder = (ShareHolder) rebllionList.getChildViewHolder(lastView);
                            if (fr.getIsDigg()) {
                                fr.setIsDigg(false);
                                fr.setCountDigg(fr.getCountDigg() - 1);

                                Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                lastHolder.tv_anchor_up.setDrawables(drawable, null, null, null);
                                lastHolder.tv_anchor_up.setTextColor(getResources().getColor(R.color.colorOpinionSelectNo));
                                showIcon = drawable;

                            } else {
                                fr.setIsDigg(true);
                                fr.setCountDigg(fr.getCountDigg() + 1);

                                Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                lastHolder.tv_anchor_up.setDrawables(drawable, null, null, null);
                                lastHolder.tv_anchor_up.setTextColor(getResources().getColor(R.color.colorTxRedMain_));
                                showIcon = drawable;
                                addInvitation(Constances.ADD_INTEGRAL_DOUP,false);
                            }
                        }
                        int upCount = fr.getCountDigg();
                        if (upCount > 0) {
                            lastHolder.tv_anchor_up.setText(String.valueOf(upCount));
                        } else {
                            lastHolder.tv_anchor_up.setText("点赞");
                        }

                    }
                }
            }
        });
    }

    @Override
    public void onLoadMore() {
        if (rebllionRefresh.isRefreshing()) {
            rebllionRefresh.loadMoreComplete();
        } else {
            getData(searchKeyCt.getText().toString().trim());
        }
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        mPageNo=0;
        mIsLoading = true;
        dataList.clear();
        getData(searchKeyCt.getText().toString().trim());
    }

    @Override
    public void OnTopicSelected(Integer selectInteger, TopicContent tp) {

    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(rebllionList, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(rebllionList, -1);
    }
}
